﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using DB.SchemaSync.Library.Models;

namespace DB.SchemaSync.Library
{
	public enum ActionType
	{
		Create = 1,
		Alter = 2,
		Drop = 3,
		Rebuild = 4
	}	

	/// <summary>
	/// Relates a set of DbObjects with a set of SQL commands
	/// For example, two column additions can relate to a single table rebuild, which is one script block
	/// </summary>
	public class ScriptBlock
	{
		public ActionType ActionType { get; set; }


		/// <summary>
		/// 关联的db对象
		/// </summary>
		public IEnumerable<DbObject> Objects { get; set; }

		public IEnumerable<string> Commands { get; set; }

		/// <summary>
		/// Set for Alter operations to represent what will be overwritten in the destination database
		/// </summary>
		public IEnumerable<DbObject> DestinationObjects { get; set; }

		/// <summary>
		/// Set for Alter operations to represent what will be overwritten in the destination database
		/// </summary>
		public IEnumerable<string> DestinationCommands { get; set; }

		/// <summary>
		/// Returns all commands for the block each followed by the SQL syntax batch separator
		/// </summary>
		public IEnumerable<string> GetCommands(SqlSyntax syntax)
		{
			foreach (string cmd in Commands)
			{
				yield return cmd;
				yield return syntax.BatchSeparator;
			}
		}

        /// <summary>
        /// 根据选择对象输出sql
        /// </summary>
        public IEnumerable<string> GetCommandsCheckSelected(SqlSyntax syntax)
        {
            foreach (string cmd in Commands)
            {
				//没有被选中的对象忽略
                if (
                    DestinationObjects != null 
                    && DestinationObjects.Any(x => !x.IsSelect))
                {
					continue;
                }

                //没有被选中的对象忽略
				if (Objects != null
                    && Objects.Any(x => !x.IsSelect))
                {
					continue;
                }

                yield return cmd;
                yield return syntax.BatchSeparator;
            }
        }

		public override string ToString()
		{
			return Objects?.First() + ": " + Commands?.First();
		}
	}
}